package org.jeecg.modules.basedata.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.beust.jcommander.internal.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.ComUtil;
import org.jeecg.common.util.DateUtil;
import org.jeecg.common.util.SsoUtil;
import org.jeecg.common.util.StringUtils;
import org.jeecg.entity.basedata.*;
import org.jeecg.entity.car.CarInfo;
import org.jeecg.entity.charge.CanGeBillsVo;
import org.jeecg.entity.charge.ChargeBills;
import org.jeecg.entity.charge.ChargeFeeRuleRoom;
import org.jeecg.entity.charge.ChargeStandard;
import org.jeecg.entity.meter.Meter;
import org.jeecg.enums.base.BaseRentStatusEnum;
import org.jeecg.modules.basedata.service.IBaseFloorService;
import org.jeecg.modules.basedata.service.IBaseProjectService;
import org.jeecg.modules.basedata.service.IBaseRoomService;
import org.jeecg.modules.system.model.SysDepartTreeModel;
import org.jeecg.modules.system.model.TreeModel;
import org.jeecg.service.IFeignCarService;
import org.jeecg.service.IFeignChargeService;
import org.jeecg.service.IFeignMeterService;
import org.jeecg.vo.basedata.BaseRoomExcel;
import org.jeecg.vo.basedata.BaseRoomPage;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

 /**
 * @Description: 房间
 * @Author: jeecg-boot
 * @Date:   2019-07-03
 * @Version: V1.0
 */
@Api(tags="房间管理")
@RestController
@RequestMapping("/b/basedata/baseRoom")
@Slf4j
public class BaseRoomController {
	@Autowired
	private IBaseRoomService baseRoomService;
	@Autowired
	private IBaseProjectService baseProjectService;
	@Autowired
	private IFeignChargeService feignChargeService;
	@Autowired
	private IFeignMeterService feignMeterService;
	@Autowired
	private IFeignCarService feignCarServiceService;
	@Autowired
	private IBaseFloorService baseFloorService;
	 SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM");



	 @AutoLog(value = "获取房间下收费标准")
	 @ApiOperation(value = "获取房间下收费标准", notes = "获取房间下收费标准")
	 @GetMapping(value = "/chargeStandardList")
	 public Result<Page<ChargeStandard>> chargeStandardList(ChargeStandard chargeStandard,
                                                             @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                             @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
		 Result<Page<ChargeStandard>> result = new Result<Page<ChargeStandard>>();
		 LoginUser user = SsoUtil.getLoginUser();
		 try {
			 result = feignChargeService.chargeStandardList(chargeStandard.getRoomId(),pageNo,pageSize, user.getTenantId());
		 } catch (Exception e) {
			 log.error(e.getMessage(), e);
			 result.error500("操作失败");
		 }
		 return result;
	 }
	 @AutoLog(value = "房间关联仪表")

	 @GetMapping(value = "/meterList")
	 public Result<Page<Meter>> meterList(Meter meter,
                                                             @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                             @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
		 Result<Page<Meter>> result = new Result<Page<Meter>>();
		 LoginUser user = SsoUtil.getLoginUser();
		 try {
			 result = feignMeterService.meterList(meter.getRoomId(),pageNo,pageSize, user.getTenantId(),user.getTenantId());
		 } catch (Exception e) {
			 log.error(e.getMessage(), e);
			 result.error500("操作失败");
		 }
		 return result;
	 }
	 @GetMapping(value = "/carList")
	 public Result<Page<CarInfo>> carList(CarInfo carInfo,
											@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
											@RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
		 Result<Page<CarInfo>> result = new Result<Page<CarInfo>>();
		 LoginUser user = SsoUtil.getLoginUser();
		 try {
			 result = feignCarServiceService.carList(carInfo.getRoomId(),pageNo,pageSize, user.getTenantId());
		 } catch (Exception e) {
			 log.error(e.getMessage(), e);
			 result.error500("操作失败");
		 }
		 return result;
	 }

	 /**
	  * 查询数据 查出所有部门,并以树结构数据格式响应给前端
	  *	最小单位为floor
	  * @return
	  */
	 @AutoLog(value = "楼栋树查询")
	 @ApiOperation(value="楼栋管理-树查询", notes="楼栋管理-树查询")
	 @RequestMapping(value = "/queryFloorTreeList", method = RequestMethod.GET)
	 public Result<List<SysDepartTreeModel>> queryFloorTreeList() {
		 Result<List<SysDepartTreeModel>> result = new Result<>();
		 try {
			 List<SysDepartTreeModel> list = baseRoomService.queryFloorTreeList();
			 result.setResult(list);
			 result.setSuccess(true);
		 } catch (Exception e) {
			 log.error(e.getMessage(),e);
		 }
		 return result;
	 }
	 /**
	  * 查询数据 查出所有部门,并以树结构数据格式响应给前端
	  *	最小单位为房间
	  * @return
	  */
	 @AutoLog(value = "房间树查询")
	 @ApiOperation(value="房间管理-树查询", notes="房间管理-树查询")
	 @RequestMapping(value = "/queryRoomTreeList", method = RequestMethod.POST)
	 public Result<List<SysDepartTreeModel>> queryRoomTreeList(@RequestBody BaseRoom baseRoom) {
		 Result<List<SysDepartTreeModel>> result = new Result<>();
		 try {
			 List<SysDepartTreeModel> list = baseRoomService.queryRoomTreeList(baseRoom);
			 result.setResult(list);
			 result.setSuccess(true);
		 } catch (Exception e) {
			 log.error(e.getMessage(),e);
			 return Result.error("系统繁忙,处理异常");
		 }
		 return result;
	 }

	 /**
	  * 查询数据 查出所有部门,并以树结构数据格式响应给前端
	  *	只有房间信息 - 不包括 项目 楼栋等
	  * @return
	  */
	 @AutoLog(value = "房间信息")
	 @ApiOperation(value="房间信息查询", notes="房间信息查询")
	 @RequestMapping(value = "/findRoomTreeList", method = RequestMethod.POST)
	 public Result<List<TreeModel>> findRoomTreeList(@RequestBody BaseRoom baseRoom) {
		 Result<List<TreeModel>> result = new Result<>();
		 try {
			 List<TreeModel> list = baseRoomService.findRoomTreeList(baseRoom);
			 result.setResult(list);
			 result.setSuccess(true);
		 } catch (Exception e) {
			 log.error(e.getMessage(),e);
			 return Result.error("系统繁忙,处理异常");
		 }
		 return result;
	 }



	/**
	  * 分页列表查询
	 * @param baseRoom
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@GetMapping(value = "/list")
	public Result<IPage<BaseRoom>> queryPageList(BaseRoom baseRoom,
									  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									  HttpServletRequest req) {
		Result<IPage<BaseRoom>> result = new Result<IPage<BaseRoom>>();
		try {
			Page<BaseRoom> pageList = new Page<BaseRoom>(pageNo, pageSize);
		    pageList = baseRoomService.listByParams(pageList,baseRoom);
		    result.setSuccess(true);
			result.setResult(pageList);
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			result.error500("查询失败！");
		}
		return result;
	}


	 /**
	  * 多个房间生成账单
	  */
	 @RequestMapping("generateBatchRoomBills")
	 public Result<List<ChargeBills>> generateBatchRoomBills(@RequestParam("roomIds")String roomIds,
															 @RequestParam("spiltDate")String spiltDate) throws ParseException {
		 Result<List<ChargeBills>> listResult = new Result<>();
		 if (StringUtils.isEmpty(spiltDate)){
			 return Result.error("请选择拆分日期");
		 }
	     String tenantId = SsoUtil.getLoginUser().getTenantId();
		 List<String> roomIdList = Arrays.asList(roomIds.split(";"));
		 //所有的收费项
		 List<String> ruleIds = baseRoomService.getAllFeeItemId(roomIdList);
         //所有房间账单
		 List<ChargeBills> chargeBills = feignChargeService.queryRoomAllBills(roomIdList,tenantId);
		 Result<List<CanGeBillsVo>> generateBillsResult = generateBillsMethod(roomIdList, ruleIds, chargeBills, spiltDate, tenantId);
		 List<CanGeBillsVo> result = generateBillsResult.getResult();
		 if (result .size() <= 0){
			 List<ChargeBills> returnChargeBills = feignChargeService.queryRoomBills(roomIdList,tenantId,spiltDate);
			 listResult.setResult(returnChargeBills);
			 return listResult;
		 }
		 try {
			 //生成账单
			 feignChargeService.canCellAndGenerateRoomBills(result,tenantId);
			 List<ChargeBills> returnChargeBills = feignChargeService.queryRoomBills(roomIdList,tenantId,spiltDate);
			 listResult.setResult(returnChargeBills);
		 }catch (Exception e){
			 log.info("错误信息",e.fillInStackTrace());
		 }

		 return listResult;
	 }
 public Result<List<CanGeBillsVo>> generateBillsMethod(List<String> roomIds,List<String> ruleIds,
												List<ChargeBills> chargeBillsList,String spiltDate,String tenantId) throws ParseException {
	 Result<List<CanGeBillsVo>> listResult = new Result<>();
	 List<CanGeBillsVo> genaBillsVoList = Lists.newArrayList();//生成集合
	 DateUtil dateUtil = DateUtil.builder().build();
	 	for (String strRoom:roomIds){
		 for (String ruleId:ruleIds){
			 //判断最后一次缴费账单 单个收费项判断
			 List<Date> payDateList = Lists.newArrayList(); //已支付
			 List<Date> generateLastDateList = Lists.newArrayList(); //已支付
			 CanGeBillsVo generateBillsVo = new CanGeBillsVo();//生成
			 Date payLastDate  = null;
			 Date generateLastDate  = null;
			 for (ChargeBills cb:chargeBillsList){
				 if (strRoom.equals(cb.getRoomId()) && cb.getFeeitemId().equals(ruleId)){
					 if (cb.getZjSkrq() != null){
						 Date parse = sdf.parse(cb.getZjCny());
						 payDateList.add(parse);
					 }
					 generateLastDateList.add(sdf.parse(cb.getZjCny()));
				 }
			 }
			 Date spiltDateCome = sdf.parse(spiltDate);
			 //最大缴费日期
			 if ( payDateList.size() > 0) {
				 payLastDate = Collections.max(payDateList);
				 if (payLastDate.compareTo(spiltDateCome) > 0 ){
					 //已支付大于选择拆分日期 故不可拆分
					 return Result.error("当前房间已支付账单最后月为"+spiltDate+"不可合并");
				 }
			 }
			 if (generateLastDateList.size() > 0 ) {
				 generateLastDate = Collections.max(generateLastDateList);
				 if ( generateLastDate.compareTo(spiltDateCome) < 0 ){
					 //生成到该拆分日期的账单
					 generateBillsVo.setRoomId(strRoom);
					 generateBillsVo.setFeeItemId(ruleId);
					 generateBillsVo.setPayDate(spiltDate);
					 generateBillsVo.setTenantId(tenantId);
					 String s = dateUtil.addMonth(sdf.format(generateLastDate));
					 generateBillsVo.setStartDate(s);
					 genaBillsVoList.add(generateBillsVo);
				 }
			 }
		 }
	 }
	 listResult.setResult(genaBillsVoList);
	 	return listResult;
 }


	@AutoLog(value = "房间查询-获取未出租房间信息")
 	@ApiOperation(value="房间查询-获取未出租房间信息", notes="房间查询-获取未出租房间信息")
	@GetMapping("/getByRentStatus")
	public Result<List<BaseRoom>> getByRentStatus(@RequestParam(name="floorId",required=true) String floorId){
		Result<List<BaseRoom>> result = new Result<List<BaseRoom>>();
		try {
			List<BaseRoom> baseRoomList = baseRoomService.getByRentStatus(floorId, BaseRentStatusEnum.BASE_RENT_STATUS_NONE.getCode());
			if (baseRoomList == null || baseRoomList.size() == 0){
				result.setSuccess(false);
				result.setMessage("当前楼栋下所有房间已经租赁。");
			}else {
				result.setResult(baseRoomList);
				result.setSuccess(true);
			}
		}catch (Exception e){
			log.error(e.getMessage(),e);
			result.error500("查询失败！");
		}
		return result;
	}

	/**
	  *   添加
	 * @param baseRoom
	 * @return
	 */
	@PostMapping(value = "/add")
	public Result<BaseRoom> add(@RequestBody BaseRoom baseRoom) {
		Result<BaseRoom> result = new Result<BaseRoom>();
		try {
			BaseFloor floor =   baseFloorService.getById(baseRoom.getFloorId());
			if (floor == null){
				return Result.error("选择的楼栋在系统中不存在!");
			}
			int count = baseRoomService.count(Wrappers.<BaseRoom>query().lambda().eq(BaseRoom::getFloorId,baseRoom.getFloorId())
					.eq(BaseRoom::getName,baseRoom.getName()).eq(BaseRoom::getDelFlag,0));
			if (count > 0){
				return Result.error("当前楼宇下已存在房间["+baseRoom.getName()+"],请勿重复录入!");
			}
			baseRoomService.save(baseRoom);
			result.success("添加成功！");
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			result.error500("操作失败");
		}
		return result;
	}
	
	/**
	  *  编辑
	 * @return
	 */
	@PutMapping(value = "/edit")
	public Result<BaseRoom> edit(@RequestBody BaseRoom baseRoom) {
		BaseRoom baseRoomEntity = baseRoomService.getById(baseRoom.getId());
		if(baseRoomEntity == null) {
			return Result.error("未找到对应实体");
		}
		int count = baseRoomService.count(Wrappers.<BaseRoom>query().lambda().eq(BaseRoom::getFloorId,baseRoom.getFloorId())
				.eq(BaseRoom::getName,baseRoom.getName()).eq(BaseRoom::getDelFlag,0).ne(BaseRoom::getId,baseRoom.getId()));
		if (count > 0){
			return Result.error("当前楼宇下已存在房间["+baseRoom.getName()+"],请勿重复录入!");
		}
		baseRoomService.updateById(baseRoom);
		return Result.ok("修改成功!");
	}
	
	/**
	  *   通过id删除
	 * @param id
	 * @return
	 */
	@DeleteMapping(value = "/delete")
	public Result<BaseRoom> delete(@RequestParam(name="id",required=true) String id) {
		Result<BaseRoom> result = new Result<BaseRoom>();
		BaseRoom baseRoom = baseRoomService.getById(id);
		if(baseRoom==null) {
			result.error500("未找到对应实体");
		}else {
			baseRoomService.delMain(id);
			result.success("删除成功!");
		}
		
		return result;
	}
	 /**
	  * 房间拆分
	  * @param  生成新房间
	  * @return
	  */
	 @RequestMapping("spiltRoom")
	 public Result<?> spiltRoom(@RequestBody BaseRoom baseRoom) throws ParseException {
	 	Result<Object> result = new Result<>();
	 	DateUtil dateUtil = DateUtil.builder().build();
		 String tenantId = SsoUtil.getLoginUser().getTenantId();
	 	if (StringUtils.isEmpty(baseRoom.getSpiltDate())){
		 	return Result.error("请选择拆分日期");
	 	}
	 	if (baseRoom.getBillsStatus() == 0){
	 		//此处为欠费账单
			//获取最后缴费账单
            ChargeBills  chargeBills = feignChargeService.getMaxPayBills(baseRoom.getId(),tenantId);
            if (chargeBills != null) {
				Date spiltDateComPare = sdf.parse(chargeBills.getZjCny());
				Date spiltDate = sdf.parse(baseRoom.getSpiltDate());
				if (spiltDateComPare.compareTo(spiltDate) < 0) {
					//已支付大于选择拆分日期 故不可拆分
					return Result.error("当前房间收费项:[" + chargeBills.getFeeName() + "]已支付账单最后月为{" + spiltDateComPare + "}不可拆分");
				}
				//作废大于拆分日期账单
				List<String> roomIds = Lists.newArrayList();
				roomIds.add(baseRoom.getId());
				feignChargeService.canCellBills(roomIds, baseRoom.getSpiltDate(), tenantId);
			}
		 }else if (baseRoom.getBillsStatus() == 1){
	 		//作废所有账单
			List<String> roomIds = Lists.newArrayList();
			roomIds.add(baseRoom.getId());
			feignChargeService.canCellAllBills(roomIds,tenantId);
		}
	 	List<BaseRoom> newRoomList = Lists.newArrayList();
	 	BaseRoom entity = baseRoomService.getById(baseRoom.getId());
		 for (int i= 0 ;i<baseRoom.getAreaList().size();i++){
			 BaseRoom br = new BaseRoom();
			 br.setId(String.valueOf(IdWorker.getId()));
			 br.setName(baseRoom.getNumList().get(i));
			 br.setBuildArea(new BigDecimal(baseRoom.getAreaList().get(i)));
			 br.setFeeStartDate(baseRoom.getFeeStartDateList().get(i));
			 br.setSplitType(2);
			 br.setSplitRefId(baseRoom.getId());
			 // 前端未传，需要后台查询
			 br.setProjectId(entity.getProjectId());
			 br.setFloorId(entity.getFloorId());
			 newRoomList.add(br);
		 }
		 try {
			 baseRoomService.saveBatch(newRoomList);
			  //更新老房间拆分日期，
			 baseRoomService.updateSpiltDate(baseRoom);
			 //绑定新房间收费项
			 List<ChargeFeeRuleRoom> chargeFeeRuleRoomList = Lists.newArrayList();
			 List<String> roomIds = Lists.newArrayList();
			 roomIds.add(baseRoom.getId());
			 List<String> feeItemIds = baseRoomService.getAllFeeItemId(roomIds);
			 for (BaseRoom br:newRoomList){
				 for (String ft : feeItemIds){
					 ChargeFeeRuleRoom chargeFeeRuleRoom = new ChargeFeeRuleRoom();
					 chargeFeeRuleRoom.setFeeId(ft);
					 chargeFeeRuleRoom.setProjectId(baseRoom.getProjectId());
					 chargeFeeRuleRoom.setRoomId(br.getId());
					 chargeFeeRuleRoom.setFloorId(br.getFloorId());
					 chargeFeeRuleRoomList.add(chargeFeeRuleRoom);
				 }
			 }
			 feignChargeService.saveBatchFeeRoom(chargeFeeRuleRoomList);
			 result.setSuccess(true);
			 result.setMessage("拆分成功");
		 }catch (Exception e){
			 log.info("错误信息",e.fillInStackTrace());
		 }
		 return result;
	 }
	 /**
	  * 房间合并
	  */
	 @RequestMapping("mergeRoom")
	 public Result mergeRoom(@RequestBody BaseRoom baseRoom){
		 Result<Object> result = new Result<>();
		 String tenantId = SsoUtil.getLoginUser().getTenantId();
		 try{
			List<String> idList = baseRoom.getIdList();
			if (baseRoom.getBillsStatus() == 0){
				//此处为欠费账单
				//获取最后缴费账单
				for (String str:idList){
					ChargeBills  chargeBills = feignChargeService.getMaxPayBills(str,tenantId);
					if (chargeBills != null) {
						Date spiltDateComPare = sdf.parse(chargeBills.getZjCny());
						Date spiltDate = sdf.parse(baseRoom.getSpiltDate());
						if (spiltDateComPare.compareTo(spiltDate) < 0) {
							//已支付大于选择拆分日期 故不可合并
							return Result.error("当前房间收费项:[" + chargeBills.getFeeName() + "]已支付账单最后月为{" + spiltDateComPare + "}不可合并");
						}
					}
                  }
               //作废大于截止日期账单
				feignChargeService.canCellBills(idList,baseRoom.getSpiltDate(),tenantId);
			}else if (baseRoom.getBillsStatus() == 1){
				//作废所有账单
				feignChargeService.canCellAllBills(idList,tenantId);
			}
			//获取合并前房间号

			List<BaseRoom> roomist = Lists.newArrayList();
			for (String num : idList) {
				BaseRoom byBaseRoom = baseRoomService.getByBaseRoom(num);
				BaseRoom baseRoom1 = new BaseRoom();
				baseRoom1.setId(byBaseRoom.getId());
				baseRoom1.setName(StrUtil.format("{}(已合并)",byBaseRoom.getName()));
				roomist.add(baseRoom1);
			 }

			//生成新的房间
			BaseRoom br = new BaseRoom();
			br.setId(String.valueOf(IdWorker.getId()));
			br.setName(baseRoom.getName());
			br.setBuildArea(baseRoom.getBuildArea());
			br.setFeeStartDate(baseRoom.getFeeStartDate());
			br.setSplitType(2);
			br.setSplitRefId(baseRoom.getId());
			br.setProjectId(baseRoom.getProjectId());
			br.setFloorId(baseRoom.getFloorId());
			List<BaseRoom> newRoomList = Lists.newArrayList();
			newRoomList.add(br);
			//绑定新房间收费项
//			List<ChargeFeeRuleRoom> chargeFeeRuleRoomList = Lists.newArrayList();
//			List<String> feeItemIds = baseRoomService.getAllFeeItemId(baseRoom.getId());
//			for (BaseRoom br2:newRoomList){
//				for (String ft : feeItemIds){
//					ChargeFeeRuleRoom chargeFeeRuleRoom = new ChargeFeeRuleRoom();
//					chargeFeeRuleRoom.setFeeId(ft);
//					chargeFeeRuleRoom.setProjectId(baseRoom.getProjectId());
//					chargeFeeRuleRoom.setRoomId(br2.getId());
//					chargeFeeRuleRoom.setFloorId(br2.getFloorId());
//					chargeFeeRuleRoomList.add(chargeFeeRuleRoom);
//				}
//			}
			//保存新生成的房间
			baseRoomService.saveBatch(newRoomList);
			//保存新房间收费项
			//feignChargeService.saveBatchFeeRoom(chargeFeeRuleRoomList);
			//更新房间名
			 if (CollUtil.isNotEmpty(roomist)) {
			 	for (BaseRoom room : roomist) {
			 		room.setSpiltDate(cn.hutool.core.date.DateUtil.formatDateTime(new Date()));
			 		room.setRoomStatus(12);
					baseRoomService.updateById(room);
				}
			 }
			result.setSuccess(true);
			result.setMessage("合并成功");
		 }catch (Exception e){
			 log.info("错误信息",e.fillInStackTrace());
			result.error500("操作失败");
		 }
		 return result.ok("合并成功");
	 }
	 /**
	  * 获取租户或者业主
	  */
	 @RequestMapping("getRoomListByTC")
	 public  Result< List<SysDepartTreeModel>> getRoomListByTC (@RequestParam("roomStatus") String roomStatus,
													   @RequestParam("floorId") String floorId){
		 Result<List<SysDepartTreeModel>> listResult = new Result<>();
		 List<SysDepartTreeModel> sysDepartTreeModels = Arrays.asList();
		 if("1".equals(roomStatus)){//租户
			 sysDepartTreeModels = baseRoomService.queryTenantList(floorId);

		 }
		 if("2".equals(roomStatus)){//业主
			 sysDepartTreeModels   =  baseRoomService.queryCustomerList(floorId);
		 }
		  listResult.setResult(sysDepartTreeModels);
		  return listResult;
	 }

	 /**
       *  批量删除
      * @param ids
      * @return
      */
	@DeleteMapping(value = "/deleteBatch")
	public Result<BaseRoom> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		Result<BaseRoom> result = new Result<BaseRoom>();
		if(ids==null || "".equals(ids.trim())) {
			result.error500("参数不识别！");
		}else {
			this.baseRoomService.delBatchMain(Arrays.asList(ids.split(",")));
			result.success("删除成功!");
		}
		return result;
	}
	
	/**
	  * 通过id查询
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/queryById")
	public Result<BaseRoomPage> queryById(@RequestParam(name="id",required=true) String id) {
		Result<BaseRoomPage> result = new Result<BaseRoomPage>();
		BaseRoomPage baseRoomPage = baseRoomService.selectByMainId(id);
		if(baseRoomPage==null) {
			result.error500("未找到对应实体");
		}else {
			result.setResult(baseRoomPage);
			result.setSuccess(true);
		}
		return result;
	}


  /**
      * 导出excel
   *
   * @param request
   * @param response
   */
  @RequestMapping(value = "/exportXls")
  public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response, BaseRoom baseRoom) {
	  LoginUser user = SsoUtil.getLoginUser();
	  Page<BaseRoom> page = new Page<BaseRoom>(1, baseFloorService.list().size());

      //Step.2 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      List<BaseRoomPage> pageList = new ArrayList<BaseRoomPage>();
      Page<BaseRoom> baseRoomList = baseRoomService.listByParams(page, baseRoom);
      for (BaseRoom b : baseRoomList.getRecords())
      {
          BaseRoomPage vo = new BaseRoomPage();
		  String roomAddress = baseRoomService.getRoomAddress(b.getId());
		  vo.setAddress(roomAddress);
		  BeanUtils.copyProperties(b, vo);
          pageList.add(vo);
      }
      //导出文件名称
      mv.addObject(NormalExcelConstants.FILE_NAME, "房间列表");
      mv.addObject(NormalExcelConstants.CLASS, BaseRoomPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("房间列表数据", "导出人:" + user.getRealname(), "导出信息"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
  }

	 /**
	  * 通过excel导入数据
	  *
	  * @param request
	  * @param response
	  * @return
	  */
	 @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	 public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		 for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			 // 获取上传文件对象
			 MultipartFile file = entity.getValue();
			 ImportParams params = new ImportParams();
			 int titleRow = 0;
			 params.setTitleRows(titleRow);
			 params.setHeadRows(titleRow);
			 params.setNeedSave(true);
			 try {
				 List<BaseRoomExcel> baseRoomExcelList = ExcelImportUtil.importExcel(file.getInputStream(), BaseRoomExcel.class, params);
				 if(baseRoomExcelList.size() <= 0){
					 return Result.error("文件内容为空，导入失败!");
				 }
				 //禁止同一房间一次性做多种操作  例：1038 先迁出->出租
				 Set<String> setPrimary = new HashSet<>();
				 for (BaseRoomExcel excel : baseRoomExcelList){
					 setPrimary.add(excel.getFloorName()+excel.getRoomName());
				 }
				 if (setPrimary.size() != baseRoomExcelList.size()){
					 return Result.error("同一楼宇同一房间不允许一次性导入多条数据，导入失败！");
				 }
				 int failureNum = 0;
				 StringBuilder failureMsg = new StringBuilder();
				 //房间信息
				 List<BaseRoom> baseRooms = new ArrayList<>();
				 //业主信息
				 List<BaseCustomer> baseCustomers = new ArrayList<>();
				 for (BaseRoomExcel baseRoomExcel: baseRoomExcelList){
					 titleRow++;
					 if (StringUtils.isBlank(baseRoomExcel.getProjectName())){
						 failureMsg.append("<br/>第").append(titleRow).append("行：请输入项目名称; ");
						 failureNum++;
						 continue;
					 }
					 BaseProject baseProject = baseProjectService.getProjectByName(baseRoomExcel.getProjectName());
					 if (baseProject == null) {
						 failureMsg.append("<br/>第").append(titleRow).append("行：填写的项目名称系统中不存在; ");
						 failureNum++;
						 continue;
					 }
					 if (StringUtils.isBlank(baseRoomExcel.getFloorName())){
						 failureMsg.append("<br/>第").append(titleRow).append("行：请输入楼宇名称; ");
						 failureNum++;
						 continue;
					 }
					 BaseFloor baseFloor = baseFloorService.queryFloorName(baseProject.getId(), baseRoomExcel.getFloorName());
					 if (baseFloor == null){
						 failureMsg.append("<br/>第").append(titleRow).append("行：填写的楼宇名称系统中不存在; ");
						 failureNum++;
						 continue;
					 }
					 if (StringUtils.isBlank(baseRoomExcel.getRoomName())){
						 failureMsg.append("<br/>第").append(titleRow).append("行：请输入房间名称; ");
						 failureNum++;
						 continue;
					 }
					 if (baseRoomExcel.getFeeStartDate() == null){
						 failureMsg.append("<br/>第").append(titleRow).append("行：请输入起始收费日期; ");
						 failureNum++;
						 continue;
					 }
					/* SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					 baseRoomExcel.setFeeStartDate(sdf.parse(baseRoomExcel.getFeeStartDate()));*/
					 if (StringUtils.isBlank(baseRoomExcel.getFloorNum())){
						 failureMsg.append("<br/>第").append(titleRow).append("行：请输入房间楼层; ");
						 failureNum++;
						 continue;
					 }
					 while (baseRoomExcel.getFloorNum().endsWith(".0")){
						 baseRoomExcel.setFloorNum(baseRoomExcel.getFloorNum().substring(0, baseRoomExcel.getFloorNum().length() - 2));
					 }
					 if (!ComUtil.isNumber(baseRoomExcel.getFloorNum())){
						 failureMsg.append("<br/>第").append(titleRow).append("行：房间楼层请输入正整数; ");
						 failureNum++;
						 continue;
					 };
					 while (baseRoomExcel.getRoomName().endsWith(".0")){
						 baseRoomExcel.setRoomName(baseRoomExcel.getRoomName().substring(0,baseRoomExcel.getRoomName().length() - 2 ));
					 }
					 BaseRoom br = baseRoomService.getBaseRoomByName(baseRoomExcel.getRoomName(), baseFloor.getId());
					 if (br != null){
						 failureMsg.append("<br/>第").append(titleRow).append("行：填写的房间名称系统中已存在; ");
						 failureNum++;
						 continue;
					 }
					 if (baseRoomExcel.getRoomProperty() == null){
						 failureMsg.append("<br/>第").append(titleRow).append("行：请输入房间属性; ");
						 failureNum++;
						 continue;
					 }

					 if (baseRoomExcel.getBuildArea() == null){
						 failureMsg.append("<br/>第").append(titleRow).append("行：请输入建筑面积; ");
						 failureNum++;
						 continue;
					 }
					 String roomId = String.valueOf(IdWorker.getId());
					 baseRoomExcel.setProjectId(baseProject.getId());
					 baseRoomExcel.setFloorId(baseFloor.getId());
					 BaseRoom room = new BaseRoom();
					 BeanUtils.copyProperties(baseRoomExcel, room);
					 BaseCustomer baseCustomer = new BaseCustomer();
					 BeanUtils.copyProperties(baseRoomExcel, baseCustomer);

					 //特殊字段需要单独设置值
					 //room.setRoomStatus(baseRoomExcel.getRoomStatus()+"");
					 room.setId(roomId);
					 room.setName(baseRoomExcel.getRoomName());
					 room.setRoomProperty(baseRoomExcel.getRoomProperty());

					 baseCustomer.setRoomId(roomId);
					 baseRooms.add(room);
					 baseCustomers.add(baseCustomer);
				 }
				 if (failureNum > 0){
					 return Result.error("文件导入失败:" + failureMsg.toString());
				 }
				 //baseRoomService.saveBatch(baseRooms);
				 //baseCustomerService.saveBatch(baseCustomers);
				 baseRoomService.addRoomCustomer(baseRooms, baseCustomers);
				 return Result.ok("文件导入成功！数据行数:" + baseRoomExcelList.size());
			 } catch (Exception e) {
				 log.error(e.getMessage(),e);
				 return Result.error("文件导入失败:"+e.getMessage());
			 } finally {
				 try {
					 file.getInputStream().close();
				 } catch (IOException e) {
					 e.printStackTrace();
				 }
			 }
		 }
		 return Result.ok("文件导入失败！");
	 }


	 /**
	  * 查询房间数据
	  * @return
	  */
	 @AutoLog(value = "房间数据查询")
	 @ApiOperation(value="房间数据查询", notes="房间数据查询")
	 @RequestMapping(value = "/getByBaseRoom", method = RequestMethod.GET)
	 public Result<BaseRoom> getByBaseRoom(@RequestParam(name="id",required=true) String id){
		 Result<BaseRoom> result = new Result<>();
		 try {
			 BaseRoom room = baseRoomService.getByBaseRoom(id);
			 result.setResult(room);
			 result.setSuccess(true);
		 }catch (Exception e){
			 log.error(e.getMessage(),e);
		 }
		 return  result;
	 }

	 /**
	  * 删除时判断房间下是否有业主或租户绑定
	  * @param
	  * @return
	  */
	 @GetMapping(value = "/getPeopeleCount")
	 public Result<Integer> getPeopeleCount(BaseRoom baseRoom) {
		 Integer count = 0;
		 try{
			 count= baseRoomService.getPeopeleCount(baseRoom.getId());
			 return Result.ok(count);
		 }catch (Exception e ){
			 e.printStackTrace();
			 return Result.error("内部异常");
		 }
	 }

	 /**
	  * 删除时判断房间下是否有业主或租户绑定
	  * @param
	  * @return
	  */
	 @GetMapping(value = "/getPeopeleCounts")
	 public Result<Integer> getPeopeleCounts(@RequestParam(name="ids",required=true) String ids) {
		 Integer count = 0;
		 try{
			 count= baseRoomService.getPeopeleCounts(ids.split(","));
			 return Result.ok(count);
		 }catch (Exception e ){
			 e.printStackTrace();
			 return Result.error("内部异常");
		 }
	 }

	 /**
	  * 通过房间编号查询
	  * @param floorId
	  * @return
	  */
	 @RequestMapping(value = "/queryByFloorId")
	 public Result<List<RoomVo>> queryByFloorId(@RequestParam(name="floorId",required=true) String floorId) {
		 Result<List<RoomVo>> result = new Result<List<RoomVo>>();
		 try {
		 	List<RoomVo> list = new ArrayList();
			 if(StringUtils.isNotEmpty(floorId)){
				 list = baseRoomService.getByFloorId(floorId);
			 }
			 result.setSuccess(true);
			 result.setResult(list);
		 } catch (Exception e) {
			 log.error(e.getMessage(),e);
			 result.error500("查询失败！");
		 }
		 return result;
	 }
	 /**
	  * 房间收费项
	  */
	 @RequestMapping("/queryRoomFeeList")
	 public Result<IPage<BaseRoom>> queryRoomFeeList(BaseRoom baseRoom,
													@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
													@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
													HttpServletRequest req){
		 Result<IPage<BaseRoom>> result = new Result<IPage<BaseRoom>>();
		 try {
			 Page<BaseRoom> pageList = new Page<BaseRoom>(pageNo, pageSize);
			 pageList = baseRoomService.queryRoomFeeList(pageList,baseRoom);
			 result.setSuccess(true);
			 result.setResult(pageList);
		 } catch (Exception e) {
			 log.error(e.getMessage(),e);
			 result.error500("查询失败！");
		 }
		 return result;
	 }
	 /**
	  * 获取项目下的房间
	  */
	 @RequestMapping("getAllRoomList")
     public Result<IPage<BaseRoom>> getRoomList(@RequestParam("projectId")String projectId,
											   @RequestParam(value = "feeRuleId",required = false) String feeRuleId,
											   @RequestParam(value = "roomId",required = false)String roomId,
											   @RequestParam(value = "floorId",required = false)String floorId,
											   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
											   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize){
		 Result<IPage<BaseRoom>> result = new Result<IPage<BaseRoom>>();
		 Page<BaseRoom> pageList = new Page<BaseRoom>(pageNo, pageSize);
		 System.out.println(floorId);
		 pageList = baseRoomService.getRoomList(pageList,projectId,feeRuleId,roomId,floorId);
		 result.setSuccess(true);
		 result.setResult(pageList);
		 return result;
	 }
 }


